// fileUpload.vue
<template>
  <div class="upload">
    <el-upload
      v-model:file-list="fileList"
      action="/erpPlatApi/common/upload"
      :list-type="listType"
      :limit="limit"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-upload="beforeAvatarUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
    >
      <el-icon>
        <Plus />
      </el-icon>
    </el-upload>
    <el-image-viewer
      v-if="imgView"
      :url-list="urlList"
      :initial-index="initialIndex"
      hide-on-click-modal
      @close="imgViewClose"
    />
  </div>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import { Plus } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import pdf from "@/assets/pdf.png";
import xlsx from "@/assets/xlsx.png";
import docx from "@/assets/docx.png";
import ZIP from "@/assets/ZIP.png";

defineOptions({
  name: "FileUpload"
});

// 传值
const props = defineProps({
  modelValue: {
    type: Array,
    default: () => {
      return [];
    }
  },
  listType: {
    type: String,
    default: "picture-card"
  },
  limit: {
    type: Number //允许上传文件的最大数量
  },
  disabled: {
    type: Boolean,
    default: false
  },

  multiple: {
    //是否支持多选文件
    type: Boolean,
    default: false
  },
  fileType: {
    type: Array,
    default() {
      return [];
    }
  },
  maxSize: {
    //允许上传的文件大小 0 ~ 20(单位M)
    type: Number,
    default: 2
  }
});
const emit = defineEmits(["update:modelValue"]);

const fileList = ref([]);
const fileSuccess = ref([]);
const fileTypes = ref("");
// 文件上传之前
const beforeAvatarUpload = file => {
  fileTypes.value = file.name.match(/\.[^.]+$/g)[0].replace(/\./g, "");
  // console.log(file)
  // 允许上传的文件格式props.fileType = ['jpg','jpeg','png','pdf','zip', ...]
  if (
    props.fileType.length &&
    !props.fileType.includes(file.name.match(/\.[^.]+$/g)[0].replace(/\./g, ""))
  ) {
    ElMessage({
      message: `允许上传的格式: ${props.fileType.join(" | ")}`,
      type: "warning"
    });
    return false;
  }
  // 允许上传的文件大小 file.size单位是字节 转换(file.size / 1024) kb,转换(file.size/1024/1024)M
  // console.log(file.size) 小于等于 20M  (props.maxSize 单位是M)
  if (file.size / 1024 / 1024 >= props.maxSize) {
    ElMessage({
      message: `允许上传的文件大小 0 ~ ${props.maxSize} M`,
      type: "warning"
    });
    return false;
  }
};
// 上传成功
// console.log(getImgUrl('icon/pdf.svg'))
const handleSuccess = (response, uploadFile, uploadFiles) => {
  if (response.code !== 200) {
    ElMessage.error(response.msg);
    return false;
  } else {
    const picurl = localStorage.getItem("picurl");
    fileSuccess.value.push({ url: picurl + response.data }) / fileListFun();
    emit("update:modelValue", fileList);
  }
};

const fileListFun = () => {
  fileList.value = [];
  if (Array.isArray(fileSuccess.value) && fileSuccess.value.length) {
    fileList.value = fileSuccess?.value.map(item => {
      if (/.pdf$/.test(item.url)) {
        item = {
          url: pdf, //用一个pdf图标代替显示图片
          showUrl: item.url,
          realUrl: item.url
        };
      } else if (/.xlsx$/.test(item.url)) {
        item = {
          url: xlsx, //用一个xlsx图标代替显示图片
          showUrl: item.url,
          realUrl: item.url
        };
      } else if (/.doc$/.test(item.url) || /.docx$/.test(item.url)) {
        // console.log(item)
        item = {
          url: docx,
          showUrl: item.url,
          realUrl: item.url
        };
      } else if (/.zip$/.test(item.url) || /.rar$/.test(item.url)) {
        item = {
          url: ZIP, //用一个zip图标代替显示图片
          showUrl: item.url,
          realUrl: item.url
        };
      } else if (/(.jpg|.png|.jpeg)$/.test(item.url)) {
        item = {
          url: item.url,
          realUrl: item.url
        };
      } else {
        item = {
          url: item.url,
          realUrl: item.url
        };
      }
      // console.log(item);
      return item;
    });
  }
};
const handleError = (error, uploadFile, uploadFiles) => {
  // console.log('error', error)
  // console.log('uploadFile', uploadFile)
  // console.log('uploadFiles', uploadFiles)
};

//删除
const handleRemove = (uploadFile, uploadFiles) => {
  const findIndex = fileSuccess.value.findIndex(item => {
    return item.url === uploadFile.showUrl;
  });
  fileSuccess.value.splice(findIndex, 1);
  fileListFun();
  emit("update:modelValue", fileList);
};
const imgView = ref(false);
const urlList = ref([]);
const initialIndex = ref(0);
//预览
const handlePreview = file => {
  if (!/(.jpg|.png|.jpeg|.webp|.svg)$/.test(file.url)) {
    if (/.pdf$/) {
      window.open(file.url, "_blank");
    }
  } else {
    imgView.value = true;
    initialIndex.value = fileList.value.findIndex(item => {
      return item.url === file.url;
    });
    urlList.value = fileList.value.map(item => {
      return item.url;
    });
  }
};
// 预览图片关闭
function imgViewClose() {
  imgView.value = false;
  urlList.value = [];
}

const newModelValue = ref(props.modelValue);

watch(
  () => newModelValue.value,
  val => {
    fileSuccess.value = val;
    fileListFun();
  },
  { immediate: true, deep: true }
);
</script>

<style lang="scss" scoped>
:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
}

:deep(.el-upload) {
  width: 100px;
  height: 100px;
  line-height: 100px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 100px;
  height: 100px;
  line-height: 100px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item-thumbnail) {
  width: 100px;
  height: 100px;
  line-height: 100px;
}

:deep(.avatar) {
  width: 100px;
  height: 100px;
}
</style>
